package com.jf3q.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jf3q.admin.service.impl.BannerServiceImpl;
import com.jf3q.admin.utils.vo.AjaxResultVO;
import com.jf3q.common.domain.EduBanner;
import com.jf3q.common.utils.OssUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/banner")
public class BannerController {

    @Autowired
    BannerServiceImpl bannerService;
    @Autowired
    OssUtils ossUtils;

    @GetMapping("/{current}/{size}")
    //@PreAuthorize("hasAuthority('banner:list')")
    public AjaxResultVO getPage(@PathVariable ( name = "current") Integer current ,
                                @PathVariable (value = "size") Integer size){
       Page<EduBanner> page= bannerService.page(new Page<>(current, size),new LambdaQueryWrapper<EduBanner>().orderByAsc(EduBanner::getSort));
       return AjaxResultVO.success(page);
    }

    @PostMapping("/save")
    //@PreAuthorize("hasAuthority('banner:save')")
    public AjaxResultVO save(  EduBanner banner, MultipartFile file){

        //上传文件
        if(file !=null && !file.isEmpty()){
            String url = ossUtils.upload("banner", file);
            banner.setImageUrl(url);
            //如果是修改的话，把旧的文件删掉
            if(StringUtils.hasText(banner.getId())){
                EduBanner byId = bannerService.getById(banner.getId());
                ossUtils.del(byId.getImageUrl());
            }
        }
        bannerService.saveOrUpdate(banner);
        return AjaxResultVO.success();

    }

    @DeleteMapping("/{id}")
    //@PreAuthorize("hasAuthority('teacher:save')")
    @Transactional
    public AjaxResultVO del(@PathVariable String id){

        try {
            EduBanner banner = bannerService.getById(id);
            //把存到阿里云上的图片也删掉
            ossUtils.del(banner.getImageUrl());
            bannerService.removeById(id);


            return AjaxResultVO.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResultVO.error("操作失败");
        }
    }


}
